import {useEffect, useState} from "react";
import {Avatar, Button, Card, Divider, List, message, Spin, Tag, Typography} from "antd";
import {EditOutlined, IdcardOutlined, LockOutlined, StopOutlined, TeamOutlined, UserOutlined} from "@ant-design/icons";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import TokenUtils from "../../../utils/tokenUtils";
import UserBasicEdit from "../../../components/console/user/userBasicEdit";
import UserIntroEdit from "../../../components/console/user/userIntroEdit";
import {useNavigate} from "react-router-dom";

const {Title, Text, Paragraph} = Typography;

const ConsoleSettingPage = () => {
    const navigate = useNavigate();
    // 消息提示实例
    const [messageApi, contextHolder] = message.useMessage();
    // 加载状态
    const [loading, setLoading] = useState(true);
    // 用户详情数据
    const [searchUserByIdResp, setSearchUserByIdResp] = useState({});
    // 编辑模态框显示状态
    const [editUserModalVisible, setEditUserModalVisible] = useState({
        basicEdit: false,
        introductionEdit: false
    });
    // 编辑表单参数
    const [editUserParam, setEditUserParam] = useState({
        userNickname: "",
        userGender: "",
        userGenderValue: "",
        userIntroduction: ""
    });

    /**
     * 根据当前用户ID查询用户详情
     */
    const searchUserByCurrentUserId = () => {
        setLoading(true);
        RequestUtils.post(RequestApis.userManage.searchById, {
            id: TokenUtils.getCurrentUserInfo().userId
        })
            .then(res => {
                setSearchUserByIdResp(res.data.data || {});
                setLoading(false);
            })
            .catch(err => {
                messageApi.error(err.message || "获取用户信息失败");
                setLoading(false);
            });
    };

    /**
     * 提交用户编辑信息
     */
    const editUserById = (editUserParam) => {
        RequestUtils.post(RequestApis.userManage.editById, {
            id: TokenUtils.getCurrentUserInfo().userId,
            userNickname: editUserParam.userNickname,
            userGender: editUserParam.userGender,
            userIntroduction: editUserParam.userIntroduction
        }).then(() => {
            searchUserByCurrentUserId();
            messageApi.success("编辑用户信息成功");
        }).catch(err => {
            messageApi.error(err.message);
        });
    };

    /**
     * 页面初始化时加载用户信息
     */
    useEffect(() => {
        searchUserByCurrentUserId();
        // eslint-disable-next-line
    }, []);

    /**
     * 格式化日期显示
     */
    const formatDate = (date) => {
        if (!date) return "未知";
        return new Date(date).toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit"
        });
    };

    // 马卡龙色系配置
    const macaronColors = {
        bg: "#FCFCFD",
        cardBorder: "1px solid rgba(200, 200, 210, 0.5)",
        shadow: "0 8px 24px rgba(149, 157, 165, 0.08)",
        hoverShadow: "0 12px 32px rgba(149, 157, 165, 0.12)",

        // 卡片渐变
        primaryCard: "linear-gradient(135deg, #FFF0F5 0%, #E6F7FF 100%)",
        accountCard: "linear-gradient(135deg, #F0F7FF 0%, #F9F0FF 100%)",
        roleCard: "linear-gradient(135deg, #FFF7F0 0%, #FFF0F0 100%)",
        permissionCard: "linear-gradient(135deg, #F0FFF4 0%, #E6FFFA 100%)",

        // 按钮专属渐变
        basicInfoBtn: "linear-gradient(135deg, #B8E1FF 0%, #9CD3FF 100%)",
        introBtn: "linear-gradient(135deg, #FFD6E0 0%, #FFB8CC 100%)",

        // 按钮文字色
        basicInfoBtnText: "#1A73E8",
        introBtnText: "#D64970",

        // 标签颜色组
        tagColors: [
            {bg: "#FFD6E0", color: "#D64970"},
            {bg: "#B8E1FF", color: "#1A73E8"},
            {bg: "#C8E6C9", color: "#2E7D32"},
            {bg: "#FFE0B2", color: "#E65100"},
            {bg: "#E1BEE7", color: "#6A1B9A"},
            {bg: "#B2EBF2", color: "#00695C"},
        ],

        // 文本色
        textPrimary: "#5A5A75",
        textSecondary: "#8A8AA0"
    };

    return (
        <div style={{padding: '16px 0', maxWidth: "1200px", margin: "0 auto"}}>
            {contextHolder}

            {/* 加载状态 */}
            {loading ? (
                <div style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    minHeight: "500px"
                }}>
                    <Spin
                        size="large"
                        tip="加载中..."
                        style={{color: "#FFB6C1"}}
                    />
                </div>
            ) : (
                <div style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "24px",
                    padding: "0 16px"
                }}>
                    {/* 主内容区域 - 左右布局 */}
                    <div style={{
                        display: "flex",
                        flexDirection: "row",
                        gap: "24px",
                        flexWrap: "wrap"
                    }}>
                        {/* 左侧：用户基础信息卡片 */}
                        <div style={{
                            flex: "1",
                            minWidth: "300px",
                            maxWidth: "600px"
                        }}>
                            <Card
                                style={{
                                    overflow: "hidden",
                                    borderRadius: "20px",
                                    border: macaronColors.cardBorder,
                                    backgroundColor: macaronColors.primaryCard,
                                    boxShadow: macaronColors.shadow,
                                    transition: "all 0.3s ease",
                                    height: "100%"
                                }}
                                hoverable
                            >
                                <div style={{
                                    display: "flex",
                                    flexDirection: "column"
                                }}>
                                    {/* 头像区域 */}
                                    <div style={{
                                        display: "flex",
                                        flexDirection: "column",
                                        alignItems: "center",
                                        padding: "24px",
                                        flex: "0 0 auto"
                                    }}>
                                        <div style={{
                                            position: "relative",
                                            marginBottom: "24px"
                                        }}>
                                            <div style={{
                                                width: "130px",
                                                height: "130px",
                                                borderRadius: "50%",
                                                background: "linear-gradient(135deg, #FFCCD5 0%, #BBD0FF 100%)",
                                                padding: "4px",
                                                boxShadow: "0 5px 15px rgba(255, 182, 193, 0.2)"
                                            }}>
                                                <Avatar
                                                    size={122}
                                                    icon={<UserOutlined
                                                        style={{fontSize: "48px", color: macaronColors.textSecondary}}/>}
                                                    style={{
                                                        backgroundColor: "#ffffff",
                                                        transition: "transform 0.3s ease"
                                                    }}
                                                    onMouseOver={(e) => e.currentTarget.style.transform = "scale(1.05)"}
                                                    onMouseOut={(e) => e.currentTarget.style.transform = "scale(1)"}
                                                />
                                            </div>
                                            <Button
                                                icon={<EditOutlined style={{color: macaronColors.textPrimary}}/>}
                                                size="small"
                                                style={{
                                                    position: "absolute",
                                                    bottom: "-5px",
                                                    right: "-5px",
                                                    borderRadius: "50%",
                                                    width: "36px",
                                                    height: "36px",
                                                    padding: 0,
                                                    background: "#ffffff",
                                                    border: "1px solid #FFD6E0",
                                                    boxShadow: "0 3px 10px rgba(255, 182, 193, 0.2)",
                                                    transition: "all 0.2s ease"
                                                }}
                                            />
                                        </div>
                                    </div>

                                    {/* 信息区域 */}
                                    <div style={{
                                        padding: "0 24px 24px",
                                        width: "100%",
                                        boxSizing: "border-box"
                                    }}>
                                        {/* 顶部：昵称与编辑按钮 */}
                                        <div style={{
                                            display: "flex",
                                            justifyContent: "space-between",
                                            alignItems: "flex-start",
                                            marginBottom: "24px",
                                            flexWrap: "wrap",
                                            gap: "16px"
                                        }}>
                                            <Title level={3} style={{
                                                margin: 0,
                                                color: macaronColors.textPrimary
                                            }}>
                                                {searchUserByIdResp.userNickname || "未设置昵称"}
                                            </Title>

                                            {/* 编辑按钮组 */}
                                            <div style={{
                                                display: "flex",
                                                gap: "12px",
                                                flexWrap: "wrap"
                                            }}>
                                                <Button
                                                    icon={<UserOutlined
                                                        style={{marginRight: "4px", color: macaronColors.basicInfoBtnText}}/>}
                                                    style={{
                                                        borderRadius: "20px",
                                                        padding: "6px 20px",
                                                        background: macaronColors.basicInfoBtn,
                                                        color: macaronColors.basicInfoBtnText,
                                                        border: "none",
                                                        boxShadow: "0 3px 10px rgba(126, 182, 255, 0.2)",
                                                        transition: "all 0.2s ease",
                                                        minWidth: "140px"
                                                    }}
                                                    onMouseOver={(e) => {
                                                        e.currentTarget.style.boxShadow = "0 5px 15px rgba(126, 182, 255, 0.3)";
                                                        e.currentTarget.style.transform = "translateY(-2px)";
                                                    }}
                                                    onMouseOut={(e) => {
                                                        e.currentTarget.style.boxShadow = "0 3px 10px rgba(126, 182, 255, 0.2)";
                                                        e.currentTarget.style.transform = "translateY(0)";
                                                    }}
                                                    onClick={() => setEditUserModalVisible({
                                                        ...editUserModalVisible,
                                                        basicEdit: true,
                                                    })}
                                                >
                                                    编辑基础信息
                                                </Button>

                                                <Button
                                                    icon={<EditOutlined
                                                        style={{marginRight: "4px", color: macaronColors.introBtnText}}/>}
                                                    style={{
                                                        borderRadius: "20px",
                                                        padding: "6px 20px",
                                                        background: macaronColors.introBtn,
                                                        color: macaronColors.introBtnText,
                                                        border: "none",
                                                        boxShadow: "0 3px 10px rgba(255, 138, 162, 0.2)",
                                                        transition: "all 0.2s ease",
                                                        minWidth: "140px"
                                                    }}
                                                    onMouseOver={(e) => {
                                                        e.currentTarget.style.boxShadow = "0 5px 15px rgba(255, 138, 162, 0.3)";
                                                        e.currentTarget.style.transform = "translateY(-2px)";
                                                    }}
                                                    onMouseOut={(e) => {
                                                        e.currentTarget.style.boxShadow = "0 3px 10px rgba(255, 138, 162, 0.2)";
                                                        e.currentTarget.style.transform = "translateY(0)";
                                                    }}
                                                    onClick={() => setEditUserModalVisible({
                                                        ...editUserModalVisible,
                                                        introductionEdit: true
                                                    })}
                                                >
                                                    编辑个人介绍
                                                </Button>

                                                <Button
                                                    color='danger'
                                                    variant='outlined'
                                                    icon={<StopOutlined style={{marginRight: "4px"}}/>}
                                                    style={{
                                                        borderRadius: "20px",
                                                        width: '140px'
                                                    }}
                                                    onClick={() => {
                                                        messageApi.success("退出登录成功, 即将返回登录页面").then(() => {
                                                            navigate("/login")
                                                        });
                                                    }}
                                                >
                                                    退出登录
                                                </Button>
                                            </div>
                                        </div>

                                        {/* 中间：基础信息列表 */}
                                        <div style={{
                                            marginBottom: "24px",
                                            background: "rgba(255, 255, 255, 0.5)",
                                            borderRadius: "12px",
                                            padding: "16px",
                                            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.03)"
                                        }}>
                                            <Title level={5} style={{
                                                margin: "0 0 16px 0",
                                                color: macaronColors.textPrimary,
                                                display: "flex",
                                                alignItems: "center"
                                            }}>
                                                <IdcardOutlined style={{marginRight: "8px", color: "#7EB6FF"}}/>
                                                基本信息
                                            </Title>

                                            <div style={{
                                                display: "grid",
                                                gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
                                                gap: "16px"
                                            }}>
                                                <div style={{display: "flex", flexDirection: "column"}}>
                                                    <Text style={{
                                                        color: macaronColors.textSecondary,
                                                        fontSize: "13px",
                                                        marginBottom: "4px"
                                                    }}>账号名称</Text>
                                                    <Text style={{color: macaronColors.textPrimary}}>
                                                        {searchUserByIdResp.userAccount || "未知账号"}
                                                    </Text>
                                                </div>

                                                <div style={{display: "flex", flexDirection: "column"}}>
                                                    <Text style={{
                                                        color: macaronColors.textSecondary,
                                                        fontSize: "13px",
                                                        marginBottom: "4px"
                                                    }}>性别</Text>
                                                    <Text style={{color: macaronColors.textPrimary}}>
                                                        {searchUserByIdResp.userGenderValue || "未设置性别"}
                                                    </Text>
                                                </div>

                                                <div style={{display: "flex", flexDirection: "column"}}>
                                                    <Text style={{
                                                        color: macaronColors.textSecondary,
                                                        fontSize: "13px",
                                                        marginBottom: "4px"
                                                    }}>用户ID</Text>
                                                    <Text style={{color: macaronColors.textPrimary}}>
                                                        {searchUserByIdResp.id || "未知"}
                                                    </Text>
                                                </div>

                                                <div style={{display: "flex", flexDirection: "column"}}>
                                                    <Text style={{
                                                        color: macaronColors.textSecondary,
                                                        fontSize: "13px",
                                                        marginBottom: "4px"
                                                    }}>注册时间</Text>
                                                    <Text style={{color: macaronColors.textPrimary}}>
                                                        {formatDate(searchUserByIdResp.createdTime)}
                                                    </Text>
                                                </div>
                                            </div>
                                        </div>

                                        {/* 底部：个人简介 */}
                                        <div style={{
                                            background: "rgba(255, 255, 255, 0.5)",
                                            borderRadius: "12px",
                                            padding: "16px",
                                            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.03)"
                                        }}>
                                            <Title level={5} style={{
                                                margin: "0 0 12px 0",
                                                color: macaronColors.textPrimary
                                            }}>个人简介</Title>
                                            <Paragraph
                                                style={{
                                                    color: macaronColors.textSecondary,
                                                    lineHeight: "1.6",
                                                    margin: 0
                                                }}
                                                ellipsis={{rows: 3, expandable: true, symbol: "查看更多"}}
                                            >
                                                {searchUserByIdResp.userIntroduction || "该用户尚未填写个人简介"}
                                            </Paragraph>
                                        </div>
                                    </div>
                                </div>
                            </Card>
                        </div>

                        {/* 右侧：三个卡片区域 */}
                        <div style={{
                            flex: "1",
                            minWidth: "300px",
                            maxWidth: "600px",
                            display: "flex",
                            flexDirection: "column",
                            gap: "24px"
                        }}>
                            {/* 账号信息卡片 */}
                            <Card
                                title={
                                    <Title level={4} style={{
                                        margin: 0,
                                        display: "flex",
                                        alignItems: "center",
                                        color: macaronColors.textPrimary
                                    }}>
                                        <LockOutlined style={{marginRight: "8px", color: "#7EB6FF"}}/>
                                        账号安全
                                    </Title>
                                }
                                style={{
                                    borderRadius: "16px",
                                    border: macaronColors.cardBorder,
                                    backgroundColor: macaronColors.accountCard,
                                    boxShadow: macaronColors.shadow,
                                    transition: "all 0.3s ease"
                                }}
                                hoverable
                            >
                                <List
                                    dataSource={[
                                        {label: "账号状态", value: "正常"},
                                        {
                                            label: "最后登录时间",
                                            value: formatDate(searchUserByIdResp.lastLoginTime || searchUserByIdResp.createdTime)
                                        },
                                        {label: "最后修改时间", value: formatDate(searchUserByIdResp.lastModifiedTime)},
                                    ]}
                                    renderItem={item => (
                                        <List.Item style={{
                                            padding: "12px 0",
                                            borderBottom: "1px solid rgba(255,255,255,0.6)"
                                        }}>
                                            <div style={{
                                                display: "flex",
                                                justifyContent: "space-between",
                                                width: "100%"
                                            }}>
                                                <Text style={{
                                                    color: macaronColors.textSecondary,
                                                    fontSize: "14px"
                                                }}>{item.label}</Text>
                                                <Text style={{color: macaronColors.textPrimary}}>{item.value}</Text>
                                            </div>
                                        </List.Item>
                                    )}
                                />
                                <Divider style={{margin: "16px 0", backgroundColor: "rgba(255,255,255,0.5)"}}/>
                                <Button
                                    type="text"
                                    style={{
                                        width: "100%",
                                        justifyContent: "center",
                                        color: "#FF8AA2",
                                        fontSize: "14px"
                                    }}
                                >
                                    修改密码
                                </Button>
                            </Card>

                            {/* 角色信息卡片 */}
                            <Card
                                title={
                                    <Title level={4} style={{
                                        margin: 0,
                                        display: "flex",
                                        alignItems: "center",
                                        color: macaronColors.textPrimary
                                    }}>
                                        <TeamOutlined style={{marginRight: "8px", color: "#FFB88C"}}/>
                                        角色信息
                                    </Title>
                                }
                                style={{
                                    borderRadius: "16px",
                                    border: macaronColors.cardBorder,
                                    backgroundColor: macaronColors.roleCard,
                                    boxShadow: macaronColors.shadow,
                                    transition: "all 0.3s ease"
                                }}
                                hoverable
                            >
                                {searchUserByIdResp.relationRoleDtos && searchUserByIdResp.relationRoleDtos.length > 0 ? (
                                    <div style={{
                                        display: "flex",
                                        flexWrap: "wrap",
                                        gap: "10px",
                                        padding: "8px 0"
                                    }}>
                                        {searchUserByIdResp.relationRoleDtos.map((role, index) => {
                                            const colorIndex = index % macaronColors.tagColors.length;
                                            const tagColor = macaronColors.tagColors[colorIndex];
                                            return (
                                                <Tag
                                                    key={index}
                                                    style={{
                                                        padding: "6px 16px",
                                                        fontSize: "13px",
                                                        borderRadius: "20px",
                                                        backgroundColor: tagColor.bg,
                                                        color: tagColor.color,
                                                        border: "none",
                                                        boxShadow: "0 2px 5px rgba(0,0,0,0.05)"
                                                    }}
                                                >
                                                    {role.roleName || `角色${index + 1}`}
                                                </Tag>
                                            );
                                        })}
                                    </div>
                                ) : (
                                    <Text style={{
                                        color: macaronColors.textSecondary,
                                        padding: "8px 0",
                                        display: "inline-block"
                                    }}>未分配角色</Text>
                                )}
                            </Card>

                            {/* 权限信息卡片 */}
                            <Card
                                title={
                                    <Title level={4} style={{
                                        margin: 0,
                                        display: "flex",
                                        alignItems: "center",
                                        color: macaronColors.textPrimary
                                    }}>
                                        <LockOutlined style={{marginRight: "8px", color: "#80E27E"}}/>
                                        权限信息
                                    </Title>
                                }
                                style={{
                                    borderRadius: "16px",
                                    border: macaronColors.cardBorder,
                                    backgroundColor: macaronColors.permissionCard,
                                    boxShadow: macaronColors.shadow,
                                    transition: "all 0.3s ease"
                                }}
                                hoverable
                            >
                                {searchUserByIdResp.relationPermissions && searchUserByIdResp.relationPermissions.length > 0 ? (
                                    <div style={{
                                        display: "flex",
                                        flexWrap: "wrap",
                                        gap: "10px",
                                        padding: "8px 0",
                                        maxHeight: "300px",
                                        overflowY: "auto",
                                        paddingRight: "8px"
                                    }}>
                                        {searchUserByIdResp.relationPermissions.map((permission, index) => {
                                            const colorIndex = index % macaronColors.tagColors.length;
                                            const tagColor = macaronColors.tagColors[colorIndex];
                                            return (
                                                <Tag
                                                    key={index}
                                                    style={{
                                                        padding: "6px 12px",
                                                        fontSize: "13px",
                                                        borderRadius: "20px",
                                                        backgroundColor: tagColor.bg,
                                                        color: tagColor.color,
                                                        border: "none",
                                                        boxShadow: "0 2px 5px rgba(0,0,0,0.05)",
                                                        whiteSpace: "nowrap"
                                                    }}
                                                >
                                                    <span>{permission.permissionName || `权限${index + 1}`}</span>
                                                    {permission.permissionCode && (
                                                        <span style={{
                                                            marginLeft: "6px",
                                                            fontSize: "11px",
                                                            opacity: 0.8
                                                        }}>
                                      ({permission.permissionCode})
                                    </span>
                                                    )}
                                                </Tag>
                                            );
                                        })}
                                    </div>
                                ) : (
                                    <Text style={{
                                        color: macaronColors.textSecondary,
                                        padding: "8px 0"
                                    }}>暂无权限信息</Text>
                                )}
                            </Card>
                        </div>
                    </div>
                </div>
            )}

            {/* 编辑用户基础信息模态框 */}
            <UserBasicEdit
                editUserModalVisible={editUserModalVisible}
                setEditUserModalVisible={setEditUserModalVisible}
                userDetail={searchUserByIdResp}
                editUserParam={editUserParam}
                setEditUserParam={setEditUserParam}
                editUserById={editUserById}
            />

            {/* 编辑个人介绍模态框 */}
            <UserIntroEdit
                editUserModalVisible={editUserModalVisible}
                setEditUserModalVisible={setEditUserModalVisible}
                userDetail={searchUserByIdResp}
                editUserParam={editUserParam}
                setEditUserParam={setEditUserParam}
                editUserById={editUserById}
            />
        </div>
    );
};

export default ConsoleSettingPage;



